'use strict';
const { AuthFailed } = require('@utils/http-exception');

module.exports = options => {
  return async (ctx, next) => {
    const url = ctx.request.url;
    const token = ctx.request.header.token;
    const userToken = await ctx.app.redis.get(ctx.username);
    const user = userToken ? userToken === token : userToken;
    if (!user && !options.exclude.includes(url.split('?')[0])) {
      throw new AuthFailed();
    } else {
      await next();
    }
  };
};
